package io.github.springstudent.service;

import com.gysoft.jdbc.bean.Criteria;
import com.gysoft.jdbc.bean.Joins;
import com.gysoft.jdbc.bean.SQL;
import com.gysoft.jdbc.bean.Sort;
import io.github.springstudent.bean.StockInfo;
import io.github.springstudent.bean.StockOperate;
import io.github.springstudent.bean.StockPrice;
import io.github.springstudent.dao.StockOperateDao;
import io.github.springstudent.dao.StockPriceDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author zhouning
 * @date 2022/06/25 15:09
 */
@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockPriceDao stockPriceDao;

    @Autowired
    private StockOperateDao stockOperateDao;

    @Override
    public List<StockPrice> listStockPrice() throws Exception {
        return stockPriceDao.queryWithCriteria(new Criteria().orderBy(new Sort(StockPrice::getBatch)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStockOperate(StockOperate stockOperate) throws Exception {
        stockOperateDao.insertWithSql(new SQL().insertInto(StockOperate.class, "batch,stockc,stockd,stocke,stockf")
                .values(stockOperate.getBatch(), stockOperate.getStockc(), stockOperate.getStockd(), stockOperate.getStocke(), stockOperate.getStockf()));
    }

    @Override
    public StockInfo getStockInfo() throws Exception {
        //查询最新一条股票交易数据
        Integer batch = stockOperateDao.queryIntegerWithSql(new SQL().select("max(batch)").from(StockOperate.class));
        return stockOperateDao.queryWithSql(StockInfo.class, new SQL().select("a.batch,a.stockc,a.stockd,a.stocke,a.stockf,b.pricec,b.priced,b.pricee,b.pricef")
                .from(StockOperate.class).as("a")
                .innerJoin(new Joins().with(StockPrice.class).as("b").on("a.batch", "b.batch").and("a.batch", batch)))
                .queryOne();
    }

    @Override
    public void resetStock() throws Exception {
        //初始化股票数据
        stockOperateDao.deleteWithCriteria(new Criteria().gt("id", 1));
    }
}


